<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

namespace Wilead\ApiBundle\Controller;

use FOS\RestBundle\Controller\Annotations\RequestParam;
use Nelmio\ApiDocBundle\Annotation\ApiDoc;
use FOS\RestBundle\View\RouteRedirectView;
use Wilead\IArtistBundle\Entity\Job,
    Wilead\IArtistBundle\Form\JobType,
    Wilead\IArtistBundle\Entity\JobResume;

/**
 * Description of JobsController
 *
 * @author jack
 */
class JobsController extends ApiController
{

    /**
     * @ApiDoc(
     *      description="获取招聘分类统计"
     * )
     */
    public function catcountAction()
    {
        $qb = $this->getEntityManager()->createQueryBuilder();

        $catCount = $qb->select('q.cat, COUNT(q.cat) AS catCount')->from('WileadIArtistBundle:Job', 'q')->groupBy('q.cat')->getQuery()->getResult();
        return $this->getFOSView()->setStatusCode(200)->setData($catCount);
    }

    /**
     * @ApiDoc(
     *      description="1101获取招聘详情"
     * )
     */
    public function getAction($id)
    {
        $qb = $this->getEntityManager()->getRepository('WileadIArtistBundle:Job')->createQueryBuilder('q');

        $data = $qb
            ->select('q, r, ur, u, us, qu')
            ->leftJoin('q.User', 'qu')
            ->leftJoin('q.Resumes', 'r')
            ->leftJoin('r.userResume', 'ur')
            ->leftJoin('ur.User', 'u')
            ->leftJoin('u.UserSkills', 'us')
            ->where('q.id = :id')->setParameter('id', $id)
            ->orderBy('q.id', 'DESC')
            ->addOrderBy('r.greenChannel', 'DESC')
            ->getQuery()
            ->getArrayResult();;

        $view = $this->getFOSView();
        if ($data) {
            $view->setStatusCode(200)->setData($data);
        }

        return $view;
    }

    /**
     * @ApiDoc(
     *      description="1102招聘信息发布"
     * )
     * @RequestParam(name="User", requirements="integer", description="用户ID")
     * @RequestParam(name="title", requirements="string", description="职位名称")
     * @RequestParam(name="description", requirements="string", description="职位描述")
     * @RequestParam(name="demand", requirements="string", description="职位要求")
     * @RequestParam(name="pay", requirements="string", description="待遇")
     * @RequestParam(name="cat", requirements="integer", description="分类")
     * @RequestParam(name="skills", requirements="string", description="技能")
     * @RequestParam(name="deadline", requirements="YYYY-mm-dd", description="招聘截止时间")
     * @RequestParam(name="points", requirements="string", description="定位 格式(104.06,30.67)", nullable=false)
     */
    public function addAction()
    {
        return $this->processJobs(new Job);
    }

    /**
     * @ApiDoc(
     *      description="1103招聘简历筛选",
     *      filters={
     *          {"name"="age", "dataType"="integer", "description"="年龄"},
     *          {"name"="sex", "dataType"="string", "description"="性别m男f女"},
     *          {"name"="height", "dataType"="integer", "pattern"="168,200", "description"="身高"},
     *          {"name"="bodyWeight", "dateType"="integer", "pattern"="55,78", "description"="体重"},
     *          {"name"="specialty", "dataType"="string", "description"="专业"},
     *          {"name"="liveplace", "dataType"="string", "description"="居住地"}
     *      }
     * )
     */
    public function searchResumeAction($id)
    {
        $request = $this->getRequest()->request;
        $year = intval(date('Y'));
        $emConfig = $this->getEntityManager()->getConfiguration();
        $emConfig->addCustomDatetimeFunction('YEAR', 'DoctrineExtensions\Query\Mysql\Year');
        $qb = $this->getRepository('WileadIArtistBundle:JobResume')->createQueryBuilder('q');
        $qb
            ->select('q, u, r')
            ->leftJoin('q.userResume', 'r')
            ->leftJoin('r.User', 'u')
            ->leftJoin('q.Job', 'j')
            ->where('j.id = :id')->setParameter('id', $id);

        if ($request->has('sex')) {
            $qb->andWhere('u.sex = :sex')->setParameter('sex', $request->get('sex'));
        }

        if ($request->has('specialty')) {
            $qb->andWhere('r.specialty = :specialty')->setParameter('specialty', $request->get('specialty'));
        }

        if ($request->has('liveplace')) {
            $qb->andWhere('r.liveplace = :liveplace')->setParameter('liveplace', $request->get('liveplace'));
        }

        if ($request->has('age')) {
            $age = explode(',', $request->get('age'));
            $qb->andWhere($year . ' - YEAR(r.brithday) >= :year_from')->setParameter('year_from', $age[0]);
            $qb->andWhere($year . ' - YEAR(r.brithday) <= :year_to')->setParameter('year_to', $age[1]);
        }

        if ($request->has('height')) {
            $height = explode(',', $request->get('height'));
            $qb->andWhere('r.height >= :height_from')->setParameter('height_from', $height[0]);
            $qb->andWhere('r.height <= :height_to')->setParameter('height_to', $height[1]);
        }

        if ($request->has('bodyWeight')) {
            $bodyWeight = explode(',', $request->get('bodyWeight'));
            $qb->andWhere('r.bodyWeight >= :bodyWeight_from')->setParameter('bodyWeight_from', $bodyWeight[0]);
            $qb->andWhere('r.bodyWeight <= :bodyWeight_to')->setParameter('bodyWeight_to', $bodyWeight[1]);
        }

        $qb->orderBy('q.greenChannel', 'DESC', 'q.created', 'DESC');
        return $this->getFOSView()->setData($qb->getQuery()->getArrayResult())->setStatusCode(200);
    }

    /**
     * @ApiDoc(
     *      description="1104招聘搜索接口",
     *      filters={
     *          {"name"="cat", "dataType"="integer", "description"="职位分类"},
     *          {"name"="key", "dataType"="string", "description"="关键词"},
     *          {"name"="skills", "dataType"="string", "description"="技能"},
     *          {"name"="title", "dataType"="string", "description"="职位名称"},
     *          {"name"="city", "dateType"="string", "description"="机构（剧组）所在地"},
     *          {"name"="points", "dataType"="string", "pattern"="104.092759,30.561242","description"="坐标"},
     *          {"name"="includeExpired", "dataType"="integer", "pattern"="0,1","description"="0不包括已过期1全部招聘(默认)"}
     *      }
     * )
     */
    public function searchAction()
    {
        $request = $this->getRequest()->request;

        $qb = $this->getRepository('WileadIArtistBundle:Job')->createQueryBuilder('q');

        $qb
            ->select('q, u, i')
            ->leftJoin('q.User', 'u')
            ->leftJoin('u.UserResume', 'r')
            ->leftJoin('u.UserIntroduction', 'i');
        if ($request->has('cat')) {
            $qb->andWhere('q.cat = :cat')->setParameter('cat', $request->get('cat'));
        }

        if ($request->has('skills')) {
            $qb->andWhere('q.skills = :skills')->setParameter('skills', $request->get('skills'));
        }

        if ($request->has('key')) {
            $qb->andWhere('q.description LIKE :key')->setParameter('key', '%' . $request->get('key') . '%');
        }

        if ($request->has('title')) {
            $qb->andWhere('q.title LIKE :title')->setParameter('title', '%' . $request->get('title') . '%');
        }

        if ($request->has('includeExpired') && $request->get('includeExpired') == '0') {
            $qb->andWhere('q.deadline >= :date')->setParameter('date', date('Y-m-d'));
        }

        if ($request->has('city')) {
            $qb->andWhere('i.city = :city')->setParameter('city', $request->get('city'));
        }

        if ($request->has('points')) {
            $points = explode(',', $request->get('points'));
            $qb->andWhere('(q.pointx LIKE :pointx) AND (q.pointy LIKE :pointy)')
                ->setParameter('pointx', substr($points[0], 0, 5) . '%')
                ->setParameter('pointy', substr($points[1], 0, 4) . '%');
        }

        $qb->orderBy('q.updated', 'DESC');

        return $this->getFOSView()->setData($qb->getQuery()->getArrayResult())->setStatusCode(200);
    }

    /**
     * @ApiDoc(
     *      description="1105招聘信息修改"
     * )
     * @RequestParam(name="title", requirements="string", description="职位名称")
     * @RequestParam(name="description", requirements="string", description="职位描述")
     * @RequestParam(name="demand", requirements="string", description="职位要求")
     * @RequestParam(name="pay", requirements="string", description="待遇")
     * @RequestParam(name="cat", requirements="integer", description="分类")
     * @RequestParam(name="deadline", requirements="YYYY-mm-dd", description="招聘截止时间")
     * @RequestParam(name="skills", requirements="skills", description="技能")
     * @RequestParam(name="points", requirements="string", description="定位 格式(104.06,30.67)", nullable=false)
     */
    public function editAction($id)
    {
        $entity = $this->getDoctrine()->getRepository('WileadIArtistBundle:Job')->find($id);

        return $this->processJobs($entity);
    }

    /**
     * @ApiDoc(
     *      description="1106获取招聘列表"
     * )
     */
    public function listAction()
    {
        $qb = $this->getRepository('WileadIArtistBundle:Job')->createQueryBuilder('q');

        $entity = $qb
            ->select('q, u, r, ur, uu')
            ->leftJoin('q.User', 'u')
            ->leftJoin('q.Resumes', 'r')
            ->leftJoin('r.userResume', 'ur')
            ->leftJoin('ur.User', 'uu')
            ->where('q.demand >= :current')->setParameter('current', date('Y-m-d'))
            ->orderBy('q.id', 'DESC', 'r.greenChannel', 'DESC')
            ->getQuery()
            ->getArrayResult();

        $view = $this->getFOSView();
        if ($entity) {
            $view->setStatusCode(200)->setData($entity);
        }

        return $view;
    }

    /**
     * @ApiDoc(
     *      description="1107招聘简历添加"
     * )
     * @RequestParam(name="userId", requirements="integer", description="用户ID")
     * @RequestParam(name="greenChanel", requirements="integer", description="0普通1绿色通道")
     */
    public function addResumesAction($id)
    {
        $entity = new JobResume;

        // 绿色通道
        if ($this->getRequest()->request->get('greenChanel') == '1') {
            $entity->setGreenChannel(TRUE);
        } else {
            $entity->setGreenChannel(FALSE);
        }

        $em = $this->getEntityManager();
        $entity->setUserResume($em->getReference('Wilead\IArtistBundle\Entity\UserResume', $this->getRequest()->request->get('userId')));
        $entity->setJob($em->getReference('Wilead\IArtistBundle\Entity\Job', $id));
        $em->persist($entity);
        $em->flush();
        return RouteRedirectView::create('wilead_api_job_get', array('id' => $id), 200);
    }

    /**
     * @ApiDoc(
     *      description="1108招聘简历移除"
     * )
     * @RequestParam(name="userId", requirements="integer", description="用户ID")
     */
    public function removeResumesAction($id)
    {
        $entity = $this->getEntityManager()->getRepository('WileadIArtistBundle:JobResume')->findOneBy(array(
            'userResume' => $this->getRequest()->request->get('userId'),
            'Job' => $id
        ));

        $em = $this->getEntityManager();
        if ($entity)
            $em->remove($entity);

        $em->flush();

        return RouteRedirectView::create('wilead_api_job_get', array('id' => $id), 200);
    }

    /**
     * 招聘表单处理
     */
    protected function processJobs(Job $entity)
    {
        $form = $this->createForm(new JobType(), $entity);
        $form->bind($this->getRequest());
        $validator = $this->get('validator');
        $errors = $validator->validate($entity);
        if (count($errors) == 0) {
            // 判断是否新增简历
            if ($entity->getId() === NULL) {
                $helper = new \Wilead\IArtistBundle\Helper\UserHelper($entity->getUser());
                $jobCount = $this->getUserJobCount($entity->getUser()->getId());
                // 标记是否超过发送总和
                $errMark = FALSE;
                if ($helper->isMember()) {
                    // 会员20职位
                    $errMark = ($jobCount >= 20);
                } else {
                    // 非会员3职位
                    $errMark = ($jobCount >= 3);
                }

                if ($errMark) {
                    return $this->getFOSView()->setStatusCode(200)->setData(array('status' => FALSE, 'info' => '超过允许发布招聘上限'));
                }
            }
            $points = $this->getRequest()->request->get('points');
            if (!is_null($points)) {
                $points = explode(',', $points);
            }
            $entity->setPointx($points[0]);
            $entity->setPointy($points[1]);
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();

            $view = RouteRedirectView::create('wilead_api_job_get', array('id' => $entity->getId()), 200);
        } else {
            $view = $this->getErrorsView($errors);
        }
        return $view;
    }

    /**
     * 获取用户发布的招聘数量
     * @param type $uid
     * @return type
     */
    protected function getUserJobCount($uid)
    {
        $queryBuilder = $this->getRepository('WileadIArtistBundle:Job')->createQueryBuilder('q');
        return $queryBuilder
            ->select('COUNT(q.id)')
            ->where('q.User = :user')->setParameter('user', $uid)
            ->andWhere('q.deadline < :date OR q.deadline IS NULL')->setParameter('date', date('Y-m-d'))
            ->getQuery()
            ->getSingleScalarResult();;
    }

}

?>
